<script setup lang="ts">
import { ref, computed, watch } from 'vue'

interface FacadeParams {
  minHeight: number
  maxHeight: number
  verticalInterval: number
  lineSegmentId: string
  direction: 'horizontal' | 'vertical'  // 航线方向
}

interface Props {
  visible: boolean
  segment: any
  params: FacadeParams
}

interface Emits {
  (e: 'close'): void
  (e: 'generate', params: FacadeParams): void
  (e: 'update:params', params: FacadeParams): void
  (e: 'export', params: FacadeParams): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 预览数据
const previewWaypoints = ref<number[][]>([])
const isGeneratingPreview = ref(false)

// 本地参数副本
const localParams = ref<FacadeParams>({ ...props.params })

// 监听外部参数变化
watch(() => props.params, (newVal) => {
  localParams.value = { ...newVal }
}, { deep: true })

// 监听本地参数变化，同步到外部
watch(localParams, (newVal) => {
  emit('update:params', { ...newVal })
}, { deep: true })

// 计算预览信息
const heightRange = computed(() => {
  return Math.max(0, localParams.value.maxHeight - localParams.value.minHeight)
})

const estimatedLayers = computed(() => {
  if (heightRange.value <= 0 || localParams.value.verticalInterval <= 0) return 0
  return Math.ceil(heightRange.value / localParams.value.verticalInterval) + 1
})

// 估算采样点数（仅用于垂直飞行）
const estimatedSamplePoints = computed(() => {
  if (localParams.value.direction !== 'vertical') return 0
  
  const points = props.segment?.points?.length || 0
  if (points < 2) return points
  
  // 粗略估算：假设原始点间距约为10米
  const estimatedLength = (points - 1) * 10 // 米
  const numSamples = Math.max(2, Math.ceil(estimatedLength / localParams.value.verticalInterval))
  return numSamples
})

const estimatedWaypoints = computed(() => {
  if (localParams.value.direction === 'vertical') {
    // 垂直飞行：每个采样点2个航点（最低和最高）
    return estimatedSamplePoints.value * 2
  } else {
    // 水平飞行：层数 × 点数
    const pointsPerLayer = props.segment?.points?.length || 0
    return estimatedLayers.value * pointsPerLayer
  }
})

// 关闭编辑器
function handleClose() {
  emit('close')
}

// 生成航线
function handleGenerate() {
  emit('generate', { ...localParams.value })
}

// 参数调整辅助函数
function adjustParam(key: 'minHeight' | 'maxHeight' | 'verticalInterval', delta: number, min: number, max: number) {
  const currentValue = localParams.value[key] as number
  const newValue = Math.max(min, Math.min(max, currentValue + delta))
  localParams.value[key] = newValue
}

// 生成预览数据
function generatePreviewWaypoints() {
  if (!props.segment?.points || props.segment.points.length === 0) {
    return []
  }

  const { minHeight, maxHeight, verticalInterval, direction } = localParams.value
  const points = props.segment.points
  const waypoints: number[][] = []

  if (direction === 'vertical') {
    // 垂直飞行：沿线段按水平间隔采样
    const sampledPoints: number[][] = []
    
    if (points.length >= 2) {
      let totalDistance = 0
      const distances: number[] = [0]
      
      // 计算累积距离
      for (let i = 1; i < points.length; i++) {
        const p1 = points[i]
        const p0 = points[i-1]
        if (!p1 || !p0) continue
        
        const dx = p1[0] - p0[0]
        const dy = p1[1] - p0[1]
        const dist = Math.sqrt(dx * dx + dy * dy) * 111000
        totalDistance += dist
        distances.push(totalDistance)
      }
      
      const numSamples = Math.max(2, Math.ceil(totalDistance / verticalInterval))
      for (let i = 0; i < numSamples; i++) {
        const targetDist = (totalDistance / (numSamples - 1)) * i
        
        let segmentIdx = 0
        for (let j = 0; j < distances.length - 1; j++) {
          const d1 = distances[j]
          const d2 = distances[j + 1]
          if (d1 !== undefined && d2 !== undefined && targetDist >= d1 && targetDist <= d2) {
            segmentIdx = j
            break
          }
        }
        
        const d1 = distances[segmentIdx]
        const d2 = distances[segmentIdx + 1]
        const p1 = points[segmentIdx]
        const p2 = points[segmentIdx + 1]
        
        if (d1 === undefined || d2 === undefined || !p1 || !p2) continue
        
        const t = d2 > d1 ? (targetDist - d1) / (d2 - d1) : 0
        const lng = p1[0] + (p2[0] - p1[0]) * t
        const lat = p1[1] + (p2[1] - p1[1]) * t
        
        sampledPoints.push([lng, lat])
      }
    } else {
      sampledPoints.push(...points)
    }
    
    // 每个采样点生成最低和最高两个航点
    sampledPoints.forEach((point: number[], pointIdx: number) => {
      const lng = point[0] ?? 0
      const lat = point[1] ?? 0
      const isAscending = pointIdx % 2 === 0
      
      if (isAscending) {
        waypoints.push([lng, lat, minHeight])
        waypoints.push([lng, lat, maxHeight])
      } else {
        waypoints.push([lng, lat, maxHeight])
        waypoints.push([lng, lat, minHeight])
      }
    })
  } else {
    // 水平飞行：逐层水平扫描
    const layers = Math.ceil((maxHeight - minHeight) / verticalInterval) + 1
    
    for (let layer = 0; layer < layers; layer++) {
      const height = minHeight + layer * verticalInterval
      const layerPoints = layer % 2 === 0 ? [...points] : [...points].reverse()
      
      layerPoints.forEach((point) => {
        const [lng, lat] = point
        waypoints.push([lng, lat, height])
      })
    }
  }

  return waypoints
}

// 导出为KML
function exportToKml() {
  isGeneratingPreview.value = true
  
  try {
    const waypoints = generatePreviewWaypoints()
    
    if (waypoints.length === 0) {
      alert('无法生成航点，请检查参数')
      return
    }

    // 构建KML
    const directionLabel = localParams.value.direction === 'vertical' ? '垂直飞行' : '水平飞行'
    const name = `立面_${directionLabel}_${props.segment?.name || '未命名'}_${localParams.value.minHeight}-${localParams.value.maxHeight}m`
    
    const coordinatesStr = waypoints
      .map(([lng, lat, alt]) => `${lng},${lat},${alt}`)
      .join('\n          ')

    const kml = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>${name}</name>
    <Placemark>
      <name>${name}</name>
      <visibility>1</visibility>
      <Style>
        <LineStyle>
          <color>ff00ffff</color>
          <width>2</width>
        </LineStyle>
      </Style>
      <ExtendedData>
        <Data name="direction">
          <value>${localParams.value.direction}</value>
        </Data>
        <Data name="minHeight">
          <value>${localParams.value.minHeight}</value>
        </Data>
        <Data name="maxHeight">
          <value>${localParams.value.maxHeight}</value>
        </Data>
        <Data name="interval">
          <value>${localParams.value.verticalInterval}</value>
        </Data>
        <Data name="waypointCount">
          <value>${waypoints.length}</value>
        </Data>
      </ExtendedData>
      <LineString>
        <altitudeMode>absolute</altitudeMode>
        <coordinates>
          ${coordinatesStr}
        </coordinates>
      </LineString>
    </Placemark>
  </Document>
</kml>`

    // 下载文件
    const blob = new Blob([kml], { type: 'application/vnd.google-earth.kml+xml' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${name}.kml`
    document.body.appendChild(a)
    a.click()
    URL.revokeObjectURL(url)
    a.remove()

    // 保存预览数据
    previewWaypoints.value = waypoints

    alert(`✅ KML导出成功！\n航点数量：${waypoints.length}`)
  } catch (error) {
    console.error('[Facade] 导出KML失败:', error)
    alert('导出失败：' + (error as Error).message)
  } finally {
    isGeneratingPreview.value = false
  }
}
</script>

<template>
  <div v-if="visible" class="facade-editor-overlay" @click.self="handleClose">
    <div class="facade-editor-panel">
      <div class="panel-header">
        <h3>📐 立面航线生成器</h3>
        <button class="btn-close" @click="handleClose">×</button>
      </div>
      
      <div class="panel-body">
        <!-- 基准线信息 -->
        <div class="info-section">
          <div class="section-title">基准线信息</div>
          <div class="info-item">
            <span class="label">线段名称：</span>
            <span class="value">{{ segment?.name || '未选择' }}</span>
          </div>
          <div class="info-item">
            <span class="label">线段点数：</span>
            <span class="value">{{ segment?.points?.length || 0 }}</span>
          </div>
        </div>

        <div class="divider"></div>

        <!-- 参数设置 -->
        <div class="params-section">
          <div class="section-title">参数设置</div>
          
          <!-- 航线方向 -->
          <div class="param-item">
            <label>航线方向</label>
            <div class="direction-buttons">
              <button 
                :class="['direction-btn', { active: localParams.direction === 'horizontal' }]"
                @click="localParams.direction = 'horizontal'"
              >
                <span class="icon">↔️</span>
                <span>水平飞行</span>
                <span class="desc">逐层水平扫描</span>
              </button>
              <button 
                :class="['direction-btn', { active: localParams.direction === 'vertical' }]"
                @click="localParams.direction = 'vertical'"
              >
                <span class="icon">↕️</span>
                <span>垂直飞行</span>
                <span class="desc">爬升下降扫描</span>
              </button>
            </div>
          </div>

          <!-- 最低高度 -->
          <div class="param-item">
            <label>最低高度（米）</label>
            <div class="input-group">
              <button @click="adjustParam('minHeight', -10, 0, 500)">-10</button>
              <button @click="adjustParam('minHeight', -1, 0, 500)">-1</button>
              <input type="number" v-model.number="localParams.minHeight" min="0" max="500" />
              <button @click="adjustParam('minHeight', 1, 0, 500)">+1</button>
              <button @click="adjustParam('minHeight', 10, 0, 500)">+10</button>
            </div>
          </div>

          <!-- 最高高度 -->
          <div class="param-item">
            <label>最高高度（米）</label>
            <div class="input-group">
              <button @click="adjustParam('maxHeight', -10, 1, 1000)">-10</button>
              <button @click="adjustParam('maxHeight', -1, 1, 1000)">-1</button>
              <input type="number" v-model.number="localParams.maxHeight" min="1" max="1000" />
              <button @click="adjustParam('maxHeight', 1, 1, 1000)">+1</button>
              <button @click="adjustParam('maxHeight', 10, 1, 1000)">+10</button>
            </div>
          </div>

          <!-- 间隔 -->
          <div class="param-item">
            <label>{{ localParams.direction === 'vertical' ? '水平间隔（米）' : '垂直间隔（米）' }}</label>
            <div class="input-group">
              <button @click="adjustParam('verticalInterval', -1, 0.5, 50)">-1</button>
              <button @click="adjustParam('verticalInterval', -0.5, 0.5, 50)">-0.5</button>
              <input type="number" v-model.number="localParams.verticalInterval" min="0.5" max="50" step="0.5" />
              <button @click="adjustParam('verticalInterval', 0.5, 0.5, 50)">+0.5</button>
              <button @click="adjustParam('verticalInterval', 1, 0.5, 50)">+1</button>
            </div>
            <div class="param-hint">
              {{ localParams.direction === 'vertical' ? '沿线段的点间距' : '高度层间距' }}
            </div>
          </div>

          <!-- 预览信息 -->
          <div class="info-preview">
            <div class="preview-header">预计生成</div>
            <div class="preview-grid">
              <div class="preview-item">
                <div class="preview-label">高度范围</div>
                <div class="preview-value">{{ heightRange }}m</div>
              </div>
              <div class="preview-item">
                <div class="preview-label">{{ localParams.direction === 'vertical' ? '采样点数' : '扫描层数' }}</div>
                <div class="preview-value">{{ localParams.direction === 'vertical' ? estimatedSamplePoints : estimatedLayers }}</div>
              </div>
              <div class="preview-item">
                <div class="preview-label">总航点数</div>
                <div class="preview-value">{{ estimatedWaypoints }}</div>
              </div>
            </div>
            <div class="flight-pattern">
              <div class="pattern-label">飞行模式：</div>
              <div class="pattern-desc">
                {{ localParams.direction === 'vertical' 
                  ? '沿线段采样点，每点从最低到最高（或反向），之字形路径' 
                  : '从下往上逐层水平飞行，之字形路径' }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="panel-footer">
        <button class="btn btn-cancel" @click="handleClose">取消</button>
        <button 
          class="btn btn-export" 
          @click="exportToKml"
          :disabled="isGeneratingPreview"
        >
          <span>📥</span> 导出KML
        </button>
        <button class="btn btn-generate" @click="handleGenerate">
          <span>✨</span> 生成航线
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.facade-editor-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.75);
  backdrop-filter: blur(6px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  animation: fadeIn 0.2s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.facade-editor-panel {
  background: linear-gradient(135deg, #1e1e1e 0%, #2a2a2a 100%);
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6);
  width: 520px;
  max-height: 85vh;
  overflow: hidden;
  transform: translateY(380px);
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(255, 255, 255, 0.1);
  animation: slideIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes slideIn {
  from { 
    opacity: 0;
    transform: translateY(-30px) scale(0.9);
  }
  to { 
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.02);
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-close {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: none;
  background: rgba(255, 255, 255, 0.05);
  color: #fff;
  font-size: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  line-height: 1;
}

.btn-close:hover {
  background: rgba(255, 59, 48, 0.8);
  transform: rotate(90deg);
}

.panel-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.section-title {
  font-size: 13px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.5);
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 12px;
}

.info-section {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 14px;
}

.info-item .label {
  color: rgba(255, 255, 255, 0.6);
}

.info-item .value {
  color: #fff;
  font-weight: 500;
}

.divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  margin: 20px 0;
}

.params-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.param-item label {
  display: block;
  margin-bottom: 10px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

/* 方向选择按钮 */
.direction-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.direction-btn {
  padding: 16px 12px;
  border-radius: 10px;
  border: 2px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.03);
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  text-align: center;
}

.direction-btn .icon {
  font-size: 24px;
}

.direction-btn .desc {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.4);
}

.direction-btn:hover {
  border-color: rgba(102, 126, 234, 0.5);
  background: rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.direction-btn.active {
  border-color: rgba(102, 126, 234, 0.8);
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.2) 0%, rgba(118, 75, 162, 0.2) 100%);
  color: #fff;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.direction-btn.active .desc {
  color: rgba(255, 255, 255, 0.7);
}

/* 参数提示 */
.param-hint {
  margin-top: 8px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  font-style: italic;
  text-align: center;
}

/* 输入组 */
.input-group {
  display: flex;
  gap: 6px;
  align-items: center;
}

.input-group button {
  min-width: 42px;
  height: 36px;
  padding: 0 8px;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.05);
  color: #fff;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 600;
}

.input-group button:hover {
  background: rgba(102, 126, 234, 0.5);
  border-color: rgba(102, 126, 234, 0.8);
  transform: scale(1.05);
}

.input-group button:active {
  transform: scale(0.95);
}

.input-group input {
  flex: 1;
  height: 36px;
  padding: 0 12px;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  background: rgba(255, 255, 255, 0.08);
  color: #fff;
  font-size: 14px;
  text-align: center;
  transition: all 0.2s ease;
  font-weight: 500;
}

.input-group input:focus {
  outline: none;
  border-color: rgba(102, 126, 234, 0.8);
  background: rgba(102, 126, 234, 0.15);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}

/* 预览信息 */
.info-preview {
  margin-top: 4px;
  padding: 18px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.12) 0%, rgba(118, 75, 162, 0.12) 100%);
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.25);
}

.preview-header {
  font-size: 12px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.6);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 12px;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.preview-item {
  text-align: center;
}

.preview-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 4px;
}

.preview-value {
  font-size: 20px;
  font-weight: 700;
  color: #667eea;
  text-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

/* 飞行模式说明 */
.flight-pattern {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.pattern-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  margin-bottom: 4px;
}

.pattern-desc {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.75);
  line-height: 1.5;
}

.panel-footer {
  display: flex;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(0, 0, 0, 0.2);
}

.panel-footer .btn {
  flex: 1;
  height: 44px;
  border-radius: 10px;
  border: none;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn-cancel {
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.btn-cancel:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  transform: translateY(-1px);
}

.btn-export {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: #fff;
  box-shadow: 0 4px 12px rgba(17, 153, 142, 0.4);
}

.btn-export:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(17, 153, 142, 0.5);
}

.btn-export:active:not(:disabled) {
  transform: translateY(0);
}

.btn-export:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-generate {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-generate:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);
}

.btn-generate:active {
  transform: translateY(0);
}
</style>
